package com.by.and_widget;

import android.content.Context;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewConfigurationCompat;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ViewConfiguration;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 自动滚动的ViewPager
 */
public class AutoScrollViewPage extends ViewPager implements Callback {
    private int time = 4 * 1000;
    private Timer mTimer;
    private TimerTask mTimerTask;
    private Handler mHandler = new Handler(this);
    private PagerAdapter mAdapter;

    private int mTouchSlop;

    public AutoScrollViewPage(Context context) {
        super(context);
        init(context);
    }

    private void init(Context context) {
        final ViewConfiguration configuration = ViewConfiguration.get(context);

        mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration);
    }

    public AutoScrollViewPage(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public void setDelayTime(int delaytime) {
        time = delaytime;
    }


    public void resume() {
        resetTimer();
    }

    public void pause() {
        cancelTimer();
    }

    @Override
    public void setAdapter(PagerAdapter adapter) {
        super.setAdapter(adapter);
        mAdapter = adapter;
        resetTimer();
    }

    /**
     * 重置定时器
     */
    private void resetTimer() {
        //LogUtils.e("AutoScrollViewPage resetTimer");
        if (mTimer != null) {
            mTimer.cancel();
        }

        if (getAdapter() != null && getAdapter().getCount() > 1) {
            mTimer = new Timer();
            mTimerTask = new TimerTask() {

                @Override
                public void run() {
                    mHandler.obtainMessage().sendToTarget();
                }
            };
            mTimer.scheduleAtFixedRate(mTimerTask, time, time);
        }
    }

    /**
     * 取消定时器
     */
    private void cancelTimer() {
        //LogUtils.e("AutoScrollViewPage cancelTimer");
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_MOVE:
                cancelTimer();
                resetTimer();
                break;
            case MotionEvent.ACTION_UP:
            default:
                //resetTimer();
                break;
        }
        return super.onInterceptTouchEvent(event);
    }

    private float mLastMotionX;
    private float mLastMotionY;

    private int direction = LEFT;//手动滑动的方向 , 默认自由滑动是向左
    private static final int LEFT = 0;
    private static final int RIGHT = 1;

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
//        switch (ev.getAction()) {
//            case MotionEvent.ACTION_DOWN: {
//                // Remember where the motion event started
//                mLastMotionX = ev.getX();
//                mLastMotionY = ev.getY();
//                cancelTimer();
//                break;
//            }
//            case MotionEvent.ACTION_MOVE: {
//                cancelTimer();
//                final float x = ev.getX();
//                final float xDiff = Math.abs(x - mLastMotionX);
//                final float y = ev.getY();
//                final float yDiff = Math.abs(y - mLastMotionY);
//                //水平滑动
//                if (xDiff > mTouchSlop && xDiff > yDiff) {
//                    direction = x - mLastMotionX > 0 ? RIGHT : LEFT;
//                    //触发滑动
//                    mHandler.obtainMessage().sendToTarget();
//                }
//                break;
//            }
//            case MotionEvent.ACTION_UP:
//            default:
//                //手指松开，方向复原
//                direction = LEFT;
//                //resetTimer();
//                break;
//        }
        return super.onTouchEvent(ev);
    }

    @Override
    protected void onDetachedFromWindow() {
        cancelTimer();
        super.onDetachedFromWindow();
    }

    @Override
    public boolean handleMessage(Message msg) {
        //最后一项，且方向向左
        if (getCurrentItem() == (mAdapter.getCount() - 1) && direction == LEFT) {
            setCurrentItem(0, false);
            //第一项，且方向向右
        } else if (getCurrentItem() == 0 && direction == RIGHT) {
            setCurrentItem(mAdapter.getCount() - 1, false);
        } else if (direction == LEFT) {
            setCurrentItem(getCurrentItem() + 1, true);
        } else if (direction == RIGHT) {
            setCurrentItem(getCurrentItem() - 1, false);
        }
        return true;
    }
}
